#include "server_core.hpp"
#include "../common/thread_pool.hpp"
#include "../common/user_manager.hpp"
#include "../common/room_manager.hpp"
#include <string>
#include <unistd.h>
#include <sys/socket.h>
#include <iostream>
#include <sstream>

static ThreadPool* pool = nullptr;

void init_server_core(ThreadPool* p) {
    pool = p;
}

void register_client(int fd) {
    user_manager.add_user(fd);
    std::cout << "[Server] New connection: fd=" << fd << std::endl;
    std::string ask_name = "[Server] Please enter your nickname:\n";
    send(fd, ask_name.c_str(), ask_name.size(), 0);
}

void unregister_client(int fd) {
    std::string name = user_manager.get_name(fd);
    std::string msg = "[Server] " + name + " left the chat.\n";
    for (int client : user_manager.get_all_fds()) {
        if (client != fd) {
            send(client, msg.c_str(), msg.size(), 0);
        }
    }
    std::cout << msg;
    user_manager.remove_user(fd);
    close(fd);
}

void handle_client_message(int fd, const std::string& msg) {
    pool->enqueue([fd, msg]() {
        if (user_manager.get_name(fd) == "anonymous") {
            user_manager.rename_user(fd, msg);
            std::string welcome = "[Server] Welcome, " + msg + "!\n";
            send(fd, welcome.c_str(), welcome.size(), 0);

            std::string notice = "[Server] " + msg + " joined the chat.\n";
            for (int client : user_manager.get_all_fds()) {
                if (client != fd) {
                    send(client, notice.c_str(), notice.size(), 0);
                }
            }
            std::cout << notice;
            return;
        }

        if (msg == "/who") {
            std::string list = "[Server] Online users:\n";
            for (int client : user_manager.get_all_fds()) {
                list += " - " + user_manager.get_name(client) + "\n";
            }
            send(fd, list.c_str(), list.size(), 0);
            return;
        } else if (msg.rfind("/rename ", 0) == 0) {
            std::string newname = msg.substr(8);
            if (newname.empty()) {
                std::string err = "[Server] Usage: /rename <newname>\n";
                send(fd, err.c_str(), err.size(), 0);
                return;
            }
            std::string oldname = user_manager.get_name(fd);
            user_manager.rename_user(fd, newname);
            std::string ack = "[Server] Your name is now " + newname + ".\n";
            send(fd, ack.c_str(), ack.size(), 0);
            std::string notice = "[Server] " + oldname + " is now known as " + newname + ".\n";
            for (int client : user_manager.get_all_fds()) {
                if (client != fd) {
                    send(client, notice.c_str(), notice.size(), 0);
                }
            }
            std::cout << notice;
            return;
        }
      // 在 server_core.cpp 中 handle_client_message 的 lambda 内部添加以下片段（在 /quit 之前）
      else if (msg.rfind("/kick ", 0) == 0) {
        std::istringstream iss(msg);
        std::string cmd, target;
        iss >> cmd >> target;

        // 假设管理员是 fd=3（你可以改成任意判定方式）
        if (fd != 4) {
            std::string err = "[Server] You are not authorized to kick users.\n";
            send(fd, err.c_str(), err.size(), 0);
            return;
        }

        int target_fd = user_manager.get_fd_by_name(target);
        if (target_fd == -1) {
            std::string err = "[Server] User not found.\n";
            send(fd, err.c_str(), err.size(), 0);
            return;
        }

        std::string notice = "[Server] You have been kicked from the chat.\n";
        send(target_fd, notice.c_str(), notice.size(), 0);

        std::string broadcast = "[Server] User " + target + " was kicked by admin.\n";
        for (int client : user_manager.get_all_fds()) {
            if (client != target_fd) {
                send(client, broadcast.c_str(), broadcast.size(), 0);
            }
        }

        unregister_client(target_fd);
        return;
    }

        else if (msg == "/quit") {
            std::string notice = "[Server] You have disconnected.\n";
            send(fd, notice.c_str(), notice.size(), 0);
            unregister_client(fd);
            return;
        } else if (msg.rfind("/join ", 0) == 0) {
            std::istringstream iss(msg);
            std::string cmd, room, pwd;
            iss >> cmd >> room >> pwd;
            room_manager.join_room(fd, room, pwd);
            std::string joined = "[Server] You joined room: " + room + "\n";
            send(fd, joined.c_str(), joined.size(), 0);
            return;
        } else if (msg == "/leave") {
            room_manager.leave_room(fd);
            std::string left = "[Server] You left the room.\n";
            send(fd, left.c_str(), left.size(), 0);
            return;
        } else if (msg == "/members") {
            std::string room = room_manager.get_room(fd);
            std::string members = room_manager.list_members(room);
            std::string output = "[Server] Members in room " + room + ": " + members + "\n";
            send(fd, output.c_str(), output.size(), 0);
            return;
        } else if (msg == "/room") {
            std::string room = room_manager.get_room(fd);
            std::string output = "[Server] You are in room: " + room + "\n";
            send(fd, output.c_str(), output.size(), 0);
            return;
        } else if (msg.rfind("/to ", 0) == 0) {
            std::istringstream iss(msg);
            std::string cmd, target, word;
            iss >> cmd >> target;
            std::string message;
            while (iss >> word) message += word + " ";
            int target_fd = user_manager.get_fd_by_name(target);
            if (target_fd != -1) {
                std::string out = "[PM from " + user_manager.get_name(fd) + "]: " + message + "\n";
                send(target_fd, out.c_str(), out.size(), 0);
            } else {
                std::string err = "[Server] User not found.\n";
                send(fd, err.c_str(), err.size(), 0);
            }
            return;
        }

        std::string output = "[" + user_manager.get_name(fd) + "]: " + msg + "\n";
        for (int client : user_manager.get_all_fds()) {
            if (client != fd) {
                send(client, output.c_str(), output.size(), 0);
            }
        }
    });
}

